var markdown = require('markdown').markdown,
    rmdirSync = require('./libs/utils.js'),
    http = require('http'),
    fs = require('fs');

var html = {};
var indexPage = '';

html.header = fs.readFileSync('./_includes/header.html');
html.footer = fs.readFileSync('./_includes/footer.html');

if (fs.existsSync('./_posts')) {

    // Reading markdown file from _post directory
    fs.readdir('./_posts', function(err, files) {

        if (err) {
            throw new Error("Something Wrong!");
        }

        if (!fs.existsSync('./_site')) {
            fs.mkdirSync('./_site');
        }

        // Convert .md file to .html file
        files.forEach(function(file) {

            // Get the input and output filename
            var fin = './_posts/' + file;
            var fout = './_site/' + file.replace(/md/, 'html');

            html.body = markdown.toHTML(fs.readFileSync(fin).toString());
            var content = html.header + html.body + html.footer;
            fs.writeFileSync(fout, content);

            indexPage += '<li><a href="./' + file.replace(/md/, 'html') + '">' + file.replace(/\.md/, '') + '</a></li>';
        });

        // Generate the index.html
        indexPage = html.header + '<ul>' + indexPage + '</ul>' + html.footer;
    console.log(indexPage);
    });

    fs.writeFile('./_site/index.html', indexPage, function(err) {
        if (err) throw new Error("Write File Failed!");
        console.log('Write Complete!');
    });

    /*
    http.createServer(function(req, res) {
        var url = './_site/' + url.parse(req)
    }).listen(8090, function() {
        console.log('server running at localhost:8090');
    });
    */
}

